<?php namespace Admin\Controller;
class CateGoryController extends CommonController{
	private $model;
	public function __auto(){
		$this->model = new \Common\Model\CateGory;
	} 
	//分类列表
	public function index(){
		$data=$this->model->orderBy('sort','DESC')->join('type','type_tid','=','tid')->get();
//		P($data);exit;
		if(!$data){
			View::success('请先去添加分类',U('add'));
		}
		//变为树状结构
		$data=Data::tree($data,'cname','cid','pid');
//		P($data);exit;
		View::with('data',$data);
		View::make();
	}
	
	//添加
	public function add(){
		$type =  new \Common\Model\Type;
		$data=$type->get();
		if(IS_POST){
			if($this->model->store()){
				View::success('添加成功',U('index'));
			}
			View::error($this->model->getError());
		}
		View::with('data',$data);
//		p($data);exit;
		View::make();
	}
	
	//子分类添加
	public function addSon(){
		//添加
		if(IS_POST){
			if($this->model->store()){
				View::success('添加成功',U('index'));
			}
			View::error($this->model->getError());
		}
		
		//获得所属分类
		$cid=Q('get.cid',0,'intval');
		$cate=$this->model->where("cid={$cid}")->join('type','type_tid','=','tid')->find();
//		p($cate);exit;
		View::with('cate',$cate);
		View::make();
	}
	
	//分类编辑
	public function edit(){
		$type =  new \Common\Model\Type;
		$data=$type->get();
		//修改
		if(IS_POST){
			if($this->model->edit()){
				View::success('修改成功',U('index'));
			}
			View::error($this->model->getError());
		}
		//获得旧数据
		$cid=Q('get.cid',0,'intval');
		$oldData=$this->model->where("cid={$cid}")->find();
		View::with('oldData',$oldData);
		$cateData=Data::tree($this->model->getNoMy($cid),'cname');
		View::with('cateData',$cateData);
		View::with('data',$data);
		View::make();
		
	}
	
	//删除
	public function del(){
		$cid=Q('get.cid',0,'intval');
		
		//子分类上移
		//pluck直接获取值
		$pid=$this->model->where("cid={$cid}")->pluck('pid');
		//找到当前分类的所有子集把pid改成被删除分类的子集
		$this->model->where("pid={$cid}")->update(array('pid'=>$pid));
		
		//执行删除
		$this->model->where("cid={$cid}")->delete();
		View::success('删除成功');
	}
	
}





 ?>